<template>
  <CardDialog
    v-model:visible="show"
    width="80%"
    :title="`${
      alarmInfo.eventType === '0'
        ? '关注记录详情'
        : (getDictLabel(alarmInfo.alarmType, alarmTypeList, { value: 'value', label: 'name' }) || '') + '报警详情'
    }`"
    @close="close"
  >
    <div class="alarm-detail">
      <div class="detail-head">
        <!-- info -->
        <div class="head-row">
          <div class="head-name">{{ alarmInfo.eventType === '0' ? '关注记录' : '报警记录' }}</div>
          <div class="head-col" v-for="(item, index) in columnList.info.list" :key="index">
            <div class="col-label">{{ item.name }}{{ item.name ? '：' : '' }}</div>
            <div class="col-span" v-if="item.format">{{ item.format(alarmInfo) }}</div>
            <div class="col-span" v-else>{{ alarmInfo[item.prop] }}</div>
          </div>
        </div>
        <!-- radar -->
        <div class="head-row">
          <div class="head-name">{{ columnList.radar.title }}</div>
          <div class="head-col" v-for="(item, index) in columnList.radar.list" :key="index">
            <div class="col-label">{{ item.name }}：</div>
            <div class="col-span" v-if="item.format">{{ item.format(alarmInfo.eventRadarVO) }}</div>
            <div class="col-span" v-else>
              {{ alarmInfo.eventRadarVO[item.prop] }} <span v-if="alarmInfo.eventRadarVO[item.prop]">{{ item.util }}</span>
            </div>
          </div>
        </div>
        <!-- ais -->
        <div class="head-row">
          <div class="head-name">{{ columnList.ais.title }}</div>
          <div class="head-col" v-for="(item, index) in columnList.ais.list" :key="index">
            <div class="col-label">{{ item.name }}：</div>
            <div class="col-span" v-if="item.format">{{ item.format(alarmInfo.aisStatic) }}</div>
            <div class="col-span" v-else>
              {{ alarmInfo.aisStatic[item.prop] }} <span v-if="alarmInfo.aisStatic[item.prop]">{{ item.util }}</span>
            </div>
          </div>
        </div>
      </div>
      <!-- 内容展示 -->
      <div class="detail-content">
        <div class="detail-left">
          <LeftTpl ref="leftTplRef" :alarmInfo="alarmInfo" />
        </div>
        <div class="detail-middle"></div>
        <div class="detail-right">
          <div class="alarm-card alarm-card-images">
            <div class="alarm-card-title">抓拍图片</div>
            <div class="alarm-card-content alarm-card-images-content" id="alarm_card_images" :style="`height: ${imageHeight}`">
              <a-image-preview-group>
                <div class="alarm-images-card" v-for="(item, index) in imgList" :key="index">
                  <a-image :width="150" :src="`${aiFileUrl}${item.imagesUrl}`" />
                </div>
              </a-image-preview-group>
            </div>
          </div>
          <div class="alarm-card alarm-card-video" :class="{ 'alarm-card-fill-video': alarmInfo.eventType === '0' }">
            <div class="alarm-card-title">监控录像</div>
            <div class="alarm-card-content alarm-card-video-content">
              <div class="alarm-video-table">
                <div class="alarm-video-head" :style="getTotalWidth(tableOptions)">
                  <div
                    class="head-col"
                    v-for="(item, index) in tableOptions"
                    :key="index"
                    :style="`min-width: ${item.width}px;width: ${item.proportion()}%`"
                  >
                    {{ item.name }}
                  </div>
                </div>
                <div class="alarm-video-body" :style="getTotalWidth(tableOptions)">
                  <div class="body-content">
                    <div class="body-row" v-for="(row, rIndex) in videoList" :keY="rIndex">
                      <div
                        class="row-item"
                        v-for="(item, index) in tableOptions"
                        :key="index"
                        :style="`min-width: ${item.width}px;width: ${item.proportion()}%`"
                      >
                        <div class="opera-col" v-if="item.type === 'opera'">
                          <CaretRightFilled @click="handlePlayBackVideo(row)" />
                          <DownloadOutlined @click="handleDownloadVideo(row)" />
                        </div>
                        <div v-else>{{ row[item.prop] }}</div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="alarm-card alarm-card-sound" v-if="alarmInfo.eventType !== '0'">
            <div class="alarm-card-title">报警声音文件</div>
            <div class="alarm-card-content alarm-card-video-content">
              <div class="alarm-video-table alarm-message-table">
                <div class="alarm-video-body alarm-message-body" :style="`width: 100%`">
                  <div class="body-content">
                    <div class="body-row" v-for="(row, rIndex) in messageList" :keY="rIndex">
                      <div class="row-item" style="width: calc(100% - 50px)">
                        <div>{{ row.mp3Url }}</div>
                      </div>
                      <div class="row-item" style="width: 50px">
                        <div class="opera-col">
                          <CaretRightFilled @click="handlePlayBackMessge(row)" />
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- 底部处置 -->
      <div class="detail-bottom">
        <div class="form-item" v-if="alarmInfo.eventType === '1'">
          <div class="form-label">处置原因：</div>
          <div class="form-span">
            <a-input v-model:value="form.alarmDispose" placeholder="" size="small" />
          </div>
        </div>
        <div class="form-item" v-if="alarmInfo.eventType === '1'">
          <div class="form-label">等级：</div>
          <div class="form-span">
            <a-radio-group v-model:value="form.alarmLevel" name="radioGroup">
              <a-radio value="1" style="color: #fff">预警报警</a-radio>
              <a-radio value="2" style="color: #fff">危险报警</a-radio>
            </a-radio-group>
          </div>
        </div>
        <!-- <div class="form-item"><a-checkbox v-model:checked="form.youxiao">有效报警</a-checkbox></div> -->
        <div class="button-list">
          <div
            class="button-item"
            type="primary"
            v-if="alarmInfo.eventType === '1'"
            @click="handleSubmit"
            :style="`cursor: ${loading ? 'no-drop' : 'pointer'};`"
          >
            <div>提交</div>
          </div>
          <div class="button-item" @click="imagePlay('image')">
            <PlayCircleOutlined />
            <div>回放（图片）</div>
          </div>
          <div class="button-item" @click="imagePlay('video')">
            <PlayCircleOutlined />
            <div>回放（视频）</div>
          </div>
          <!-- <div class="button-item">
            <BookFilled />
            <div>相关记录</div>
          </div> -->
        </div>
      </div>
      <!-- mp3 -->
      <audio ref="audioPlayerRef" controls class="audio-player"></audio>
    </div>
    <!-- 回放 -->
    <PlayBack ref="playBackRef" />
    <PlayBackVideo ref="playBackVideoRef" />
  </CardDialog>
</template>
<script setup>
  import { nextTick, ref, watch, onMounted } from 'vue';
  import _ from 'lodash';
  import { message } from 'ant-design-vue';
  import { alarmTypeList } from '/@/config/strategy';
  import { getDictLabel } from '/@/utils/methods';
  import { dateFormat } from '/@/utils/date.js';
  import * as options from './options';
  // api
  import { api } from '/@/api/plat/event.js';
  import { api as imagesApi } from '/@/api/plat/event-result.js';
  import { api as videoApi } from '/@/api/plat/event-video.js';
  import { api as messageApi } from '/@/api/plat/event-message.js';
  // components
  import CardDialog from '/@/components/cardDialog/index.vue';
  import PlayBackVideo from './playBackVideo/index.vue';
  import PlayBack from './playback/index.vue';
  import LeftTpl from './leftComponents/index.vue';

  const aiFileUrl = import.meta.env.VITE_APP_AIFILE;

  const emit = defineEmits(['close', 'download', 'reload']);

  const leftTplRef = ref();
  const playBackRef = ref();
  const audioPlayerRef = ref();
  const playBackVideoRef = ref();
  const columnList = options.columnList;
  const show = ref(false);
  const imgList = ref([]);
  const videoList = ref([]);
  const messageList = ref([]);
  const alarmInfo = ref({
    eventRadarVO: {},
    aisStatic: {},
    eventType: '0',
  });
  const loading = ref(false);
  const imageHeight = ref('calc(100% - 24px)');
  const soundList = ref([]);
  const tableOptions = options.tableOptions;
  const form = ref({
    alarmDispose: undefined,
    alarmLevel: undefined,
    isDispose: 1,
  });

  function getTotalWidth(option) {
    let number = 0;
    option.forEach((item) => {
      number += item.width;
    });
    return `min-width: ${number}px`;
  }

  function getInfoById(row) {
    api.getDetailById(row.eventId).then(({ data }) => {
      let info = Object.assign({}, row, data);
      info.eventRadarVO = Object.assign({}, info, info.eventRadarVO);
      info.aisStatic = Object.assign({}, info, info.aisStatic);
      alarmInfo.value = info;
      // 处置结果获取
      const { alarmDispose, alarmLevel } = data;
      form.value = {
        alarmDispose,
        alarmLevel,
        isDispose: 1,
      };
    });
  }

  function handleSubmit() {
    if (loading.value) return;
    loading.value = true;
    const formData = form.value;
    formData.eventId = alarmInfo.value.eventId;
    formData.isProcessed = true;
    api.update(formData).then(() => {
      loading.value = false;
      message.success('操作成功');
      emit('reload');
    });
  }

  function imagePlay(type) {
    playBackRef.value.open(alarmInfo.value, type);
  }

  function getImages(row) {
    imagesApi.queryList({ targetId: row.targetId, startTime: dateFormat(new Date(row.startTime)), endTime: row.endTime }).then(({ data }) => {
      const uniqueArray = data.reduce((acc, current) => {
        const x = acc.find((item) => item.imagesUrl === current.imagesUrl);
        if (!x) {
          acc.push(current);
        }
        return acc;
      }, []);
      imgList.value = uniqueArray;
    });
  }

  function getImageUrl(val) {
    if (val.indexOf('http') < 0) {
      return `/${val}`;
    } else {
      return val;
    }
  }

  function getVideos(row) {
    videoApi.queryList({ eventId: row.eventId }).then(({ data }) => {
      videoList.value = data;
    });
  }

  function getMessages(row) {
    messageApi.queryList({ eventId: row.eventId }).then(({ data }) => {
      messageList.value = data.map((m) => {
        m.mp3Url = aiFileUrl + m.mp3Url;
        return m;
      });
    });
  }

  function handlePlayBackVideo(row) {
    playBackVideoRef.value.open(row);
  }

  function handleDownloadVideo(row) {
    // emit('download', row);
    let x = new XMLHttpRequest();
    let downloadFileUrl = row.mp4Url + '/' + dateFormat(row.startTime, 'yyyyMMdd') + '/' + row.videoId + '.mp4';
    downloadFileUrl = downloadFileUrl.replace(/^https:\/\/101\.66\.174\.148:9089/, '/wvpFileApi');
    const link = document.createElement('a');
    link.href = downloadFileUrl;
    link.download = downloadFileUrl;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }

  function handlePlayBackMessge(row) {
    audioPlayerRef.value.src = row.mp3Url; // 设置音频的 URL
    audioPlayerRef.value.play(); // 播放音频
  }

  // 暂停音频播放
  function pauseAudio() {
    audioPlayerRef.value.pause();
  }

  function close() {
    imgList.value = [];
    videoList.value = [];
    imageHeight.value = 'calc(100% - 24px)';
    form.value = {
      alarmDispose: undefined,
      alarmLevel: undefined,
      isDispose: 1,
    };
    emit('close');
  }

  function open(row) {
    getInfoById(row);
    getImages(row);
    getVideos(row);
    getMessages(row);
    show.value = true;
    nextTick(() => {
      leftTplRef.value.open();
      getImagesHeight();
    });
  }

  function getImagesHeight() {
    const mapElement = document.getElementById('alarm_card_images');
    if (mapElement) {
      imageHeight.value = mapElement.offsetHeight + 'px';
    }
  }

  watch(
    () => show.value,
    (val) => {
      if (!val) {
        leftTplRef.value.close();
      }
    }
  );

  defineExpose({ open });
</script>

<style lang="less" scoped>
  @import './index.less';
</style>
